﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.Win32;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.RegisteredServers;

namespace AppCommon
{
  public  class SqlDBInfo
    {
        public static string[] EnumAvailableSqlServers()
        {
            try
            {

              //  cbServer.Items.Clear();


                // SMO Enum Servers
                List<String> lstServer = new List<string>();
                DataTable dt = SmoApplication.EnumAvailableSqlServers(false);

                foreach (DataRow row in dt.Rows)
                {
                    if(lstServer.Contains(row["Name"].ToString()))
                        continue;
                    else
                        lstServer.Add(row["Name"].ToString());
                }

                //Registry for local
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
                String[] instances = (String[])rk.GetValue("InstalledInstances");
                if (instances.Length > 0)
                {
                    foreach (String element in instances)
                    {
                        String name = "";
                        //only add if it doesn't exist
                        if (element == "MSSQLSERVER")
                            name = System.Environment.MachineName;
                        else
                            name = System.Environment.MachineName + @"\" + element;

                        if (lstServer.Contains(name))
                            continue;
                        else
                            lstServer.Add(name);


                    }
                }

                // Registered Servers
                RegisteredServer[] rsvrs = SqlServerRegistrations.EnumRegisteredServers();

                foreach (RegisteredServer rs in rsvrs)
                {
                    String name = "";

                    name = rs.ServerInstance.Replace(".", System.Environment.MachineName)
                                            .Replace("(local)", System.Environment.MachineName)
                                            .Replace("localhost", System.Environment.MachineName);
                    //only add if it doesn't exist

                    if (lstServer.Contains(name))
                        continue;
                    else
                        lstServer.Add(name);

                }


                return lstServer.ToArray();
            }
            
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
